package com.service.user.impl;

import com.dao.ShoppingCarDao;
import com.entity.ShoppingCar;
import com.service.user.GoodService;
import com.service.user.ShoppingCarService;
import com.utils.SqlSessionGetter;

import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * 提供和购物车相关的功能实现
 *
 * 
 */
@Service
public class ShoppingCarServiceImpl implements ShoppingCarService {

  @Autowired GoodService goodService;

  /**
   * 查看商品在自己购物车中的数量
   *
   * @param userId 用户编号
   * @param goodId 商品编号
   * @return 商品在自己购物车中的数量
   */
  @Override
  public int getGoodCountInMyCar(String userId, String goodId) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    ShoppingCarDao dao = session.getMapper(ShoppingCarDao.class);
    int count = 0;
    try {
      count = dao.selectInCarCount(userId, goodId);
    } catch (BindingException exp) {
      // 没有记录集
    }
    session.close();
    return count;
  }

  /**
   * 将商品添加到购物车
   *
   * @param userId 用户编号
   * @param goodId 商品编号
   * @param count 数量
   * @return 添加成功返回条目编号，否则返回0
   */
  @Override
  public String addToMyCar(String userId, String goodId, int count) {
    String itemId = UUID.randomUUID().toString().replace("-", "");
    SqlSession session = SqlSessionGetter.getSqlSession();
    ShoppingCarDao dao = session.getMapper(ShoppingCarDao.class);
    try {
      dao.insertAShoppingCar(itemId, goodId, userId, count);
      session.commit();
    } catch (Exception exp) {
      session.close();
      return "0";
    }
    session.close();
    return itemId;
  }

  /**
   * 获取用户的购物车对应页的条目
   *
   * @param userId 用户编号
   * @param pageSize 页大小
   * @param pageIndex 页索引
   * @return 用户的购物车对应页的条目
   */
  @Override
  public List<ShoppingCar> getCarList(String userId, int pageSize, int pageIndex) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    ShoppingCarDao dao = session.getMapper(ShoppingCarDao.class);
    List<ShoppingCar> myCar = dao.selectCarList(userId, pageIndex * pageSize, pageSize);
    session.close();
    return myCar;
  }

  /**
   * 删除购物车条目
   *
   * @param itemId 购物车条目编号
   * @return 删除成功返回1，失败返回0
   */
  @Override
  public int delCarItem(String itemId) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    ShoppingCarDao dao = session.getMapper(ShoppingCarDao.class);
    int row = dao.deleteCarItem(itemId);
    session.commit();
    session.close();
    return row;
  }

  @Override
  public int getCarCount(String userId) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    ShoppingCarDao dao = session.getMapper(ShoppingCarDao.class);
    int count = dao.selectCarCount(userId);
    session.close();
    return count;
  }
}
